import formatGatewayUrl from './formatGatewayUrl';

/**
 * 格式化文件上传下载url
 * @param url
 * @param params
 */
function downloadFile(url: any, prefix: any, downloadParams = {}) {
    return new Promise<void>(resolve => {
        let iframe = document.querySelector('#downloadFrame') as HTMLIFrameElement;
        if (!iframe) {
            iframe = document.createElement('iframe');
            iframe.id = 'downloadFrame';
            iframe.style.display = 'none';
            document.body.appendChild(iframe);
        }
        // ie11 中文乱码
        iframe.src = encodeURI(`${formatGatewayUrl(`${prefix}${url}`, {}, downloadParams)}`);
        let timer = setInterval(() => {
            // @ts-ignore
            const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
            if (iframeDoc.readyState === 'complete' || iframeDoc.readyState === 'interactive') {
                clearInterval(timer)
                resolve()
            }
        }, 100);
    });
};

export default downloadFile;
